package com.runfast.waimai.web.controller.company;

import com.runfast.common.utils.SessionContext;
import com.runfast.common.web.entity.Result;
import com.runfast.waimai.dao.model.*;
import com.runfast.waimai.service.*;
import com.runfast.waimai.utils.TimeUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

/**
 * ${DESCRIPTION} 区域代理管理
 *
 * @author chenzheng
 * @create 2018-05-21 17:33
 **/
@RestController("areaAgentController")
@RequestMapping("/server/areaAgent")
public class AreaAgentController {
    @Autowired
    private BaseUserService baseUserService;
    @Autowired
    private BaseUserRoleService baseUserRoleService;
    @Autowired
    private WaiMaiRunfastAgentbusinessService waiMaiRunfastAgentbusinessService;
    @Autowired
    private BaseRoleService baseRoleService;
    @Autowired
    private RunfastGoodsSellRecordService runfastGoodsSellRecordService;
    @Autowired
    private WaiMaiRunfastAgentaccountsService waiMaiRunfastAgentaccountsService;
    /**
     * 区域代理列表带分页的
     */
    @GetMapping("/list")
    public Result list(@PageableDefault Pageable pageable,String name,String mobile){
        BaseUser admin = SessionContext.getAdmin();
        List<WaiMaiRunfastAgentbusiness> list=new ArrayList<WaiMaiRunfastAgentbusiness>();
        Integer total=null;
        WaiMaiRunfastAgentbusinessExample example=new WaiMaiRunfastAgentbusinessExample();
        WaiMaiRunfastAgentbusinessExample.Criteria exampleCriteria=example.createCriteria();
        exampleCriteria.andFlageEqualTo(1).andAgentidIsNull();
        if(StringUtils.isNotBlank(name)){
            exampleCriteria.andNameLike("%"+name+"%");
        }
        if(StringUtils.isNotBlank(mobile)){
            exampleCriteria.andMobileLike("%"+mobile+"%");
        }
        if(admin!=null && admin.getType()==1){
            list=waiMaiRunfastAgentbusinessService.selectByExampleWithPageable(example,pageable);
            if(list.size()>0){
                for(WaiMaiRunfastAgentbusiness agentbusiness:list){
                    BaseUserExample example1=new BaseUserExample();
                    example1.createCriteria().andAgentIdEqualTo(agentbusiness.getId());
                    List<BaseUser> baseUserList=baseUserService.selectByExample(example1);
                    if(baseUserList.size()>0){
                        agentbusiness.setUsername(baseUserList.get(0).getUsername());
                        agentbusiness.setRname("区域代理");
                        agentbusiness.setAgentIds(baseUserList.get(0).getAgentids());
                    }
                }
            }
            total=waiMaiRunfastAgentbusinessService.countByExample(example);
        }else{return Result.fail(null,"此功能只有总公司人员才有权限！");}
        Map<Object,Object> map=new HashMap<Object, Object>();
        map.put("list",list);
        map.put("total",total);
        return Result.ok(null,map);
    }



   /**添加代理商时使用：查询所有区域代理商*/
   @GetMapping("selectAreaAgents")
   public Result selectAreaAgents(){
       List<WaiMaiRunfastAgentbusiness> areaAgents=new ArrayList<WaiMaiRunfastAgentbusiness>();
       List<BaseUser> userList=baseUserRoleService.queryUserList(20);
       if(userList.size()>0){
           for(BaseUser user:userList){
                if(user.getAgentId()!=null && user.getState()!=null &&user.getState()==0){
                    WaiMaiRunfastAgentbusiness   areaAgent=waiMaiRunfastAgentbusinessService.selectByPrimaryKey(user.getAgentId());
                    areaAgents.add(areaAgent);
                }
           }
       }
       Integer total =areaAgents.size();
       Map<Object,Object> map=new HashMap<Object, Object>();
       map.put("areaAgents",areaAgents);
       map.put("total",total);
       return Result.ok(null,map);
   }


    /**
     * 区域代理信息
     */
    @GetMapping("/info")
    public Result info(Integer id){
        if(id==null){return Result.fail(null,"区域代理id不能为空！");}
        BaseUser u=baseUserService.selectByPrimaryKey(id);
        if(u!=null){
              if(u.getAgentId()!=null){
                  WaiMaiRunfastAgentbusiness agent=waiMaiRunfastAgentbusinessService.selectByPrimaryKey(u.getAgentId());
                  if(agent!=null && agent.getCoefficient()!=null){
                      u.setCoefficient(agent.getCoefficient());
                  }
              }
        }else{return Result.fail(null,"对应的区域代理不存在！");}
        return Result.ok(null,u);
    }
    /**
     * 保存区域代理
     */
    @PostMapping("/save")
    public Result save(@RequestBody WaiMaiRunfastAgentbusiness agentbusiness){
        BaseUser admin = SessionContext.getAdmin();
        if(admin!=null && admin.getType()==1){
             if(agentbusiness!=null && StringUtils.isNotBlank(agentbusiness.getUsername()) && StringUtils.isNotBlank(agentbusiness.getName()) && StringUtils.isNotBlank(agentbusiness.getMobile())
                     && agentbusiness.getPid()!=null && StringUtils.isNotBlank(agentbusiness.getProvince()) && agentbusiness.getCoefficient()!=null ){
                 //总部创建一级代理商
                 BaseUserExample example=new BaseUserExample();
                 example.createCriteria().andUsernameEqualTo(agentbusiness.getUsername());
                 Integer in=baseUserService.countByExample(example);
                 if(in>0){
                     return Result.fail(null,"该登录账号已经注册过了！");
                 }
                 WaiMaiRunfastAgentbusiness agent=new WaiMaiRunfastAgentbusiness();
                 agent.setCreatetime(new Date());
                 agent.setMobile(agentbusiness.getMobile());
                 agent.setName(agentbusiness.getName());
                 agent.setIshaveup(1);
                 agent.setPid(agentbusiness.getPid());
                 agent.setCid(agentbusiness.getCid());
                 agent.setTid(agentbusiness.getTid());
                 agent.setProvince(agentbusiness.getProvince());
                 agent.setCityname(agentbusiness.getCityname());
                 agent.setCountyname(agentbusiness.getCountyname());
                 agent.setCoefficient(agentbusiness.getCoefficient());
                 agent.setFlage(1);//区域代理
                 waiMaiRunfastAgentbusinessService.insert(agent);
                 //后台人员登录--只能总部人才员有权限
                 //在系统人员表中创建--一级代理的账号：用于查看其管理的代理商数据
                 BaseUser u=new BaseUser();
                 u.setRealname(agentbusiness.getName());
                 u.setCreatetime(new Date());
                 u.setUsername(agentbusiness.getUsername());
                 u.setPassword(DigestUtils.md5Hex("123456"));
                 u.setMobile(agentbusiness.getMobile());
                 u.setState(0);
                 u.setAgentId(agent.getId());
                 u.setAgentids(agentbusiness.getAgentIds());
                 u.setFlag(7);
                 baseUserService.insertSelective(u);
                 BaseUserRole userRole=new BaseUserRole();
                 userRole.setUserid(u.getId());
                 userRole.setRid(20);
                 baseUserRoleService.insertSelective(userRole);
             }else{return Result.fail(null,"传入参数不对！");}
        }else{return Result.fail(null,"此功能只有总公司人员才有权限！");}
        return Result.ok(null);
    }

    /**
     * 修改区域代理
     */
    @PostMapping("/update")
    public Result update(@RequestBody WaiMaiRunfastAgentbusiness agentbusiness){
        BaseUser admin = SessionContext.getAdmin();
        if(admin!=null && admin.getType()==1){
            if(agentbusiness!=null &&agentbusiness.getId()!=null && StringUtils.isNotBlank(agentbusiness.getUsername()) && StringUtils.isNotBlank(agentbusiness.getName()) && StringUtils.isNotBlank(agentbusiness.getMobile())
                    && agentbusiness.getPid()!=null && agentbusiness.getCoefficient()!=null ){
                BaseUserExample example1=new BaseUserExample();
                example1.createCriteria().andAgentIdEqualTo(agentbusiness.getId());
                List<BaseUser> baseUserList=baseUserService.selectByExample(example1);
                if(baseUserList.size()>0){
                    BaseUser u=baseUserList.get(0);
                    BaseUserExample example=new BaseUserExample();
                    example.createCriteria().andUsernameEqualTo(agentbusiness.getUsername()).andIdNotEqualTo(u.getId());
                    Integer in=baseUserService.countByExample(example);
                    if(in>0){
                        return Result.fail(null,"该登录账号已经注册过了！");
                    }
                    u.setRealname(agentbusiness.getName());
                    u.setModifytime(new Date());
                    u.setUsername(agentbusiness.getUsername());
                    u.setMobile(agentbusiness.getMobile());
                    if(StringUtils.isNotBlank(u.getAgentids())){
                        List<String> result = Arrays.asList(u.getAgentids().split(","));
                        for(String s:result){
                            int a = Integer.parseInt(s);
                            WaiMaiRunfastAgentbusiness agentbusiness1=waiMaiRunfastAgentbusinessService.selectByPrimaryKey(a);
                            if(agentbusiness1!=null){
                                agentbusiness1.setFlage(3);
                                agentbusiness1.setAgentname(null);
                                agentbusiness1.setAgentid(null);
                                waiMaiRunfastAgentbusinessService.updateByPrimaryKey(agentbusiness1);
                            }
                        }
                    }
                    if(StringUtils.isNotBlank(agentbusiness.getAgentIds())){
                        List<String> result = Arrays.asList(agentbusiness.getAgentIds().split(","));
                        for(String s:result){
                            int a = Integer.parseInt(s);
                            WaiMaiRunfastAgentbusiness agentbusiness1=waiMaiRunfastAgentbusinessService.selectByPrimaryKey(a);
                            if(agentbusiness1!=null){
                                agentbusiness1.setFlage(2);
                                agentbusiness1.setAgentname(agentbusiness.getName());
                                agentbusiness1.setAgentid(agentbusiness.getId());
                                waiMaiRunfastAgentbusinessService.updateByPrimaryKey(agentbusiness1);
                            }
                        }
                    }
                    u.setAgentids(agentbusiness.getAgentIds());
                    u.setFlag(7);
                    baseUserService.updateByPrimaryKeySelective(u);
                    //后台人员登录--只能总部人员才有权限
                    WaiMaiRunfastAgentbusiness agent=waiMaiRunfastAgentbusinessService.selectByPrimaryKey(u.getAgentId());
                    agent.setMobile(agentbusiness.getMobile());
                    agent.setName(agentbusiness.getName());
                    agent.setPid(agentbusiness.getPid());
                    agent.setCid(agentbusiness.getCid());
                    agent.setTid(agentbusiness.getTid());
                    if(StringUtils.isNotBlank(agentbusiness.getProvince())){
                        agent.setProvince(agentbusiness.getProvince());
                    }
                    if(StringUtils.isNotBlank(agentbusiness.getCityname())){
                        agent.setCityname(agentbusiness.getCityname());
                    }
                    if(StringUtils.isNotBlank(agentbusiness.getCountyname())){
                        agent.setCountyname(agentbusiness.getCountyname());
                    }
                    agent.setCoefficient(agentbusiness.getCoefficient());
                    waiMaiRunfastAgentbusinessService.updateByPrimaryKeySelective(agent);
                }
            }else{return Result.fail(null,"传入参数不对！");}
        }else{return Result.fail(null,"此功能只有总公司人员才有权限！");}
        return Result.ok(null);
    }




    /**修改密码*/
    @GetMapping("/setPassword")
    public Result setPassword(Integer id,String password){
        if(id!=null && StringUtils.isNotBlank(password)){
            WaiMaiRunfastAgentbusiness  agentbusiness=waiMaiRunfastAgentbusinessService.selectByPrimaryKey(id);
            if(agentbusiness!=null){
                BaseUserExample example=new BaseUserExample();
                example.createCriteria().andAgentIdEqualTo(agentbusiness.getId());
                List<BaseUser> baseUserList=baseUserService.selectByExample(example);
                if(baseUserList.size()>0){
                    BaseUser baseUser=baseUserList.get(0);
                    baseUser.setPassword(password);
                    baseUserService.updateByPrimaryKeySelective(baseUser);
                }
            }else{return Result.fail(null,"找不到对应的代理商！");}
        }else{return Result.fail(null,"传入参数不对！");}
        return Result.ok(null);
    }

    /**
     * 区域代理列表
     */
    @GetMapping("/cityManagerlist")
    public Result cityManagerlist(@PageableDefault Pageable pageable, Map<String, Object> params){
        Map<Object,Object> map1=new HashMap<Object, Object>();
        map1.put("rid",19); //城市经理的rid==19
        if(params.size()==0){
            map1.put("offset",0);
            map1.put("pageSize",50);
        }
        List<BaseUser> userList=baseUserService.selectUserByExampleWithPageable(map1);
        Integer total=baseUserService.countUserByExample(map1);
        Map<Object,Object> map=new HashMap<Object, Object>();
        map.put("list",userList);
        map.put("total",total);
        return Result.ok(null,map);
    }


    /**给区域代理指定--属于公司直属的一级代理商*/
    @GetMapping("setAgentIds")
    public Result setAgentIds(){
        WaiMaiRunfastAgentbusinessExample example=new WaiMaiRunfastAgentbusinessExample();
        example.createCriteria().andFlageEqualTo(3).andAgentidIsNull();
        List< WaiMaiRunfastAgentbusiness> agentbusinessList=waiMaiRunfastAgentbusinessService.selectByExample(example);
        return  Result.ok(null,agentbusinessList);
    }

    /**区域代理的角色*/
    @GetMapping("setRole")
    public Result  setRole(){
        BaseRoleExample example=new BaseRoleExample();
        example.createCriteria().andAgentIdIsNull().andRnameEqualTo("大区代理");
        example.or().andAgentIdIsNull().andRnameEqualTo("区域代理");
        List<BaseRole> baseRoleList=baseRoleService.selectByExample(example);
        return Result.ok(null,baseRoleList);
    }


    /**
     * 区域代理列表带分页的
     */
    @GetMapping("/AreaList")
    public Result AreaList(@PageableDefault Pageable pageable, Map<String, Object> params){
        Map<Object,Object> map1=new HashMap<Object, Object>();
        BaseUser admin = SessionContext.getAdmin();
        List<BaseUser> list=null;
        Integer total=null;
        if(admin!=null && admin.getType()==1){
            BaseUserExample example=new BaseUserExample();
            //flage=6城市经理  flage=7区域代理
            example.createCriteria().andFlagEqualTo(7);
            list=baseUserService.selectByExampleWithPageable(example,pageable);
            if(list.size()>0){
                for(BaseUser user:list){
                    List<WaiMaiRunfastAgentbusiness> waiMaiRunfastAgentbusinessList=new ArrayList<WaiMaiRunfastAgentbusiness>();
                    if(StringUtils.isNotBlank( user.getAgentids())){
                        List<String> result = Arrays.asList(user.getAgentids().split(","));
                        for(String s:result){
                            int a = Integer.parseInt(s);
                            WaiMaiRunfastAgentbusiness agentbusiness1=waiMaiRunfastAgentbusinessService.selectByPrimaryKey(a);
                            if(agentbusiness1!=null){
                                WaiMaiRunfastAgentaccountsExample example1=new WaiMaiRunfastAgentaccountsExample();
                                example1.createCriteria().andAgentidEqualTo(agentbusiness1.getId()).andByrolesEqualTo("12");
                                List<WaiMaiRunfastAgentaccounts> agentaccountsList=waiMaiRunfastAgentaccountsService.selectByExample(example1);
                                WaiMaiRunfastAgentaccounts agentaccounts=new WaiMaiRunfastAgentaccounts();
                                if(agentaccountsList.size()>0){
                                    agentaccounts=agentaccountsList.get(0);
                                }
                                map1.put("agentId",agentbusiness1.getId());
                                Map<Object,Object> map=runfastGoodsSellRecordService.cityData(map1);
                                agentbusiness1.setTotalAmount(new BigDecimal(map.get("totalMoney").toString()));
                                agentbusiness1.setTotalAgentIncome(new BigDecimal(map.get("totalAgentBusget").toString()));
                                agentbusiness1.setTotalNum(Integer.valueOf(map.get("num").toString()));
                                agentbusiness1.setRname("代理商");
                                agentbusiness1.setUsername(agentaccounts.getAccounts());
                                waiMaiRunfastAgentbusinessList.add(agentbusiness1);
                            }
                        }
                        user.setWaiMaiRunfastAgentbusinessList(waiMaiRunfastAgentbusinessList);
                    }
                }
            }
            total=baseUserService.countByExample(example);
        }else{return Result.fail(null,"此功能只有总公司人员才有权限！");}
        Map<Object,Object> map=new HashMap<Object, Object>();
        map.put("list",list);
        map.put("total",total);
        return Result.ok(null,map);
    }

     /**单个区域代理数据查询*/
     @GetMapping("/selectAreaAgent")
     public Result selectAreaAgent(Integer id,String date) throws ParseException {
         BaseUser baseUser=new BaseUser();
           if(id!=null && StringUtils.isNotBlank(date)){
               Map<Object,Object> map1=new HashMap<Object, Object>();
               baseUser=baseUserService.selectByPrimaryKey(id);
               if(baseUser!=null){
                   if(StringUtils.isNotBlank( baseUser.getAgentids())){
                       List<WaiMaiRunfastAgentbusiness> waiMaiRunfastAgentbusinessList=new ArrayList<WaiMaiRunfastAgentbusiness>();
                       List<String> result = Arrays.asList(baseUser.getAgentids().split(","));
                       for(String s:result){
                           int a = Integer.parseInt(s);
                           WaiMaiRunfastAgentbusiness agentbusiness1=waiMaiRunfastAgentbusinessService.selectByPrimaryKey(a);
                           if(agentbusiness1!=null){
                               WaiMaiRunfastAgentaccountsExample example1=new WaiMaiRunfastAgentaccountsExample();
                               example1.createCriteria().andAgentidEqualTo(agentbusiness1.getId()).andByrolesEqualTo("12");
                               List<WaiMaiRunfastAgentaccounts> agentaccountsList=waiMaiRunfastAgentaccountsService.selectByExample(example1);
                               WaiMaiRunfastAgentaccounts agentaccounts=new WaiMaiRunfastAgentaccounts();
                               if(agentaccountsList.size()>0){
                                   agentaccounts=agentaccountsList.get(0);
                               }
                               /**查询时间*/
                               List<String> result1 = Arrays.asList(date.split(","));
                               map1.put("startTime",TimeUtil.getDate(result1.get(0)));
                               map1.put("endTime",TimeUtil.getDate(result1.get(1)));
                               map1.put("agentId",agentbusiness1.getId());
                               Map<Object,Object> map=runfastGoodsSellRecordService.cityData(map1);
                               agentbusiness1.setTotalAmount(new BigDecimal(map.get("totalMoney").toString()));
                               agentbusiness1.setTotalAgentIncome(new BigDecimal(map.get("totalAgentBusget").toString()));
                               agentbusiness1.setTotalNum(Integer.valueOf(map.get("num").toString()));
                               agentbusiness1.setRname("代理商");
                               agentbusiness1.setUsername(agentaccounts.getAccounts());
                               waiMaiRunfastAgentbusinessList.add(agentbusiness1);
                           }
                       }
                       baseUser.setWaiMaiRunfastAgentbusinessList(waiMaiRunfastAgentbusinessList);
                   }
               }else{return Result.fail(null,"找不到对应的区域代理！");}
           }else{return Result.fail(null,"传入参数不对！");}
           return Result.ok(null,baseUser);
     }


    /**
     * 区域代理列表
     */
   /* @GetMapping("/select")
    //@RequiresPermissions("server:goodsSellType:select")
    public Result select(){
        List<RunfastGoodsSellType> list = runfastGoodsSellTypeService.selectByExample(null);
        return Result.ok(null,list);
    }*/


    /**
     * 删除区域代理---暂时不实现
     */
    /*@PostMapping("/delete")
    public R delete(@RequestBody Long[] roleIds){
        sysRoleService.deleteBatch(roleIds);

        return R.ok();
    }*/
}
